package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import dao.OrderDao;
import po.Cart;
import po.Dish;
import po.Orders;
import util.DBUtil;

public class OrderDaoImpl implements OrderDao {

	@Override
	public Integer addOrder(Cart cart,Integer oid) {
		Connection con = null;
		PreparedStatement pst = null;
		int count = 0;
		
		try {
			con = DBUtil.getConnection();
			con.setAutoCommit(false);
			String sql = "insert into orders(id,aid,did,oid,count) values(CART_SEQ.nextval,?,?,?,?)";
			pst = con.prepareStatement(sql);
			pst.setString(1,cart.getAid());
			pst.setInt(2, cart.getDid());
			pst.setInt(3,oid);
			pst.setInt(4, cart.getCount());
			count = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		} 
		return count;
	}
	
	public Integer getOid(){
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Integer oid = 0;
		try {
			con = DBUtil.getConnection();
			String sql = "select oid_seq.nextval as oid from dual";
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			while (rs.next()) {
				oid = rs.getInt("oid");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return oid;
	}
	
	public List<Orders> getAllOrder(String aid,HttpServletRequest request){
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Orders orders= null;
		List<Orders> orderList = new ArrayList<Orders>();
		Map<Integer,Dish> dishMap = (Map<Integer,Dish>)request.getServletContext().getAttribute("dishMap");
		try {
			con = DBUtil.getConnection();
			String sql = "select * from orders where aid = ? order by oid";
			pst = con.prepareStatement(sql);
			pst.setString(1, aid);
			rs = pst.executeQuery();
			while (rs.next()) {
				orders = new Orders();
				orders.setAid(rs.getString("aid"));
				orders.setOid(rs.getInt("oid"));
				orders.setDid(rs.getInt("did"));
				orders.setCount(rs.getInt("count"));
				orders.setOtime(rs.getTimestamp("otime"));
				orders.setDish(dishMap.get(rs.getInt("did")));
				orderList.add(orders);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return orderList;
	}
}
